const Router = require('koa-router')
const router = new Router({ prefix: '/xwzxxq' })
const u = require('../api')

router.get('/:id.html', async (ctx) => {
  // 面包屑
  let crumbsData = [{
    name: '首页',
    href: '/'
  }, {
    name: '新闻资讯',
    href: '/xwzx'
  }]
  if (!/^\d+$/.test(ctx.params.id)) {
    ctx.throw(404)
  }
  // 获取更多资讯
  let getNewsMore = await u.http({
    url: u.queryNewsList,
    params: {
      pageNum: 1,
      pageSize: 15,
      newsType: ''
    }
  })
  // 获取资讯详情
  let getNewsInfo = await u.http({
    url: u.queryNewsById,
    params: {
      id: ctx.params.id
    }
  })
  if (getNewsInfo.data.newsMap) {
    console.log(getNewsInfo.data)
    // 修改时间戳
    if (getNewsInfo.data.newsMap.addTime) {
      let d = new Date(getNewsInfo.data.newsMap.addTime).toLocaleDateString()
      d = d.replace(/\//gi, '-')
      let t = new Date(getNewsInfo.data.newsMap.addTime).toTimeString()
      t = t ? /^\d{2}:\d{2}:\d{2}/.exec(t)[0] : ''
      getNewsInfo.data.newsMap.addTimeNow = d + ' ' + t
    }
    // 追加面包屑
    crumbsData.push({
      name: `${getNewsInfo.data.newsMap.title.substr(0, 6)}...`,
      href: ''
    })
    newsInfoData = getNewsInfo.data.newsMap
  } else {
    ctx.throw(404)
  }
  // 修改TDK
  ctx.config.tdk.title = `${getNewsInfo.data.newsMap.title}-彧胜实业`
  ctx.config.tdk.description = ''
  ctx.config.tdk.keywords = ''


  await ctx.render('xwzxxq.ejs', {
    config: ctx.config,
    crumbsData,
    prevData: getNewsInfo.data.previousPageNewsMap,
    newsInfoData,
    nextData: getNewsInfo.data.nextPageNewsMap,
    newsMoreData: getNewsMore.code == 200 ? getNewsMore.data.list : []
  })
})

module.exports = router